import { Component } from "react";
import Button from "reactstrap/lib/Button";
import Col from "reactstrap/lib/Col";
import Row from "reactstrap/lib/Row";
import { IPersonState } from "./State";
import FormValidation from './FormValidation'
import { Database } from './DataBase/Database';
import { IRecordState, RecordState } from './RecordState';
import { PersonRecord } from './Types';
import { PersonalDetailsTableBuilder } from './PersonalDetailsTableBuilder';

interface IProps {
  DefaultState: IPersonState;
}

export default class PersonalDetails extends Component<IProps, IPersonState> {
  private defaultState: Readonly<IPersonState>;
  private canSave: boolean = false;
  private readonly dataLayer: Database<PersonRecord>;
  private people: IPersonState;

  constructor(props: IProps) {
    super(props);
    this.defaultState = props.DefaultState;
    this.state = props.DefaultState;
    const tableBuilder: PersonalDetailsTableBuilder = new PersonalDetailsTableBuilder()
    this.dataLayer = new Database(tableBuilder.Build())
  }

  public render() {
    let people = null;
    if (this.people) {
      const copyThis = this;
      people = this.people.map(p => {
        return (
          <Row key={p.PersonId}>
            <Col lg="6"><label>{p.firstName}</label></Col>
            <Col lg="3"><Button value={p.PersonId} color="link" onClick={copyThis.setActive}>编辑</Button></Col>
            <Col lg="3"><Button value={p.PersonId} color="link" onClick={copyThis.delete}>删除</Button></Col>
          </Row>
        )
      })
    }
    return (
      <Row>
        <Col lg="8">
          <Row>
            <Col>
              <h4 className="mb-3">个人信息</h4>
            </Col>
          </Row>
          <Row>
            <Col>
              <Row>
                <Col>
                  <label htmlFor="firstName">姓</label>
                </Col>
                <Col>
                  <label htmlFor="lastName">名</label>
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col>
              <Row>
                <Col>
                  <input
                    type="text"
                    id="firstName"
                    className="form-control"
                    placeholder="姓"
                    value={this.state.FirstName}
                    onChange={this.updateBinding}
                  />
                </Col>
                <Col>
                  <input
                    type="text"
                    id="lastName"
                    className="form-control"
                    placeholder="名"
                    value={this.state.LastName}
                    onChange={this.updateBinding}
                  />
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col>
              <Row>
                <Col>
                  <label htmlFor="addr1">地址1</label>
                </Col>
              </Row>
              <Row>
                <Col>
                  <input
                    type="text"
                    id="addr1"
                    className="form-control"
                    placeholder="地址1"
                    value={this.state.Address1}
                    onChange={this.updateBinding}
                  />
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col>
              <Row>
                <Col>
                  <label htmlFor="addr2">地址2</label>
                </Col>
              </Row>
              <Row>
                <Col>
                  <input
                    type="text"
                    id="addr2"
                    className="form-control"
                    placeholder="地址2"
                    value={this.state.Address2!}
                    onChange={this.updateBinding}
                  />
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col>
              <Row>
                <Col>
                  <label htmlFor="town">城市</label>
                </Col>
              </Row>
              <Row>
                <Col>
                  <input
                    type="text"
                    id="town"
                    className="form-control"
                    placeholder="城市"
                    value={this.state.Town}
                    onChange={this.updateBinding}
                  />
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col>
              <Row>
                <Col>
                  <label htmlFor="country">区/县</label>
                </Col>
              </Row>
              <Row>
                <Col>
                  <input
                    type="text"
                    id="country"
                    className="form-control"
                    placeholder="区/县"
                    value={this.state.Country}
                    onChange={this.updateBinding}
                  />
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col>
              <Row>
                <Col>
                  <label htmlFor="postcode">邮编</label>
                </Col>
                <Col>
                  <label htmlFor="phoneNumber">电话</label>
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col>
              <Row>
                <Col>
                  <input
                    type="text"
                    id="postcode"
                    className="form-control"
                    placeholder="邮编"
                    value={this.state.Postcode}
                    onChange={this.updateBinding}
                  />
                </Col>
                <Col>
                  <input
                    type="text"
                    id="phoneNumber"
                    className="form-control"
                    placeholder="名"
                    value={this.state.PhoneNumber}
                    onChange={this.updateBinding}
                  />
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col>
              <Row>
                <Col>
                  <label htmlFor="dateOfBirth">生日</label>
                </Col>
              </Row>
              <Row>
                <Col>
                  <input
                    type="date"
                    id="dateOfBirth"
                    className="form-control"
                    placeholder="生日"
                    value={this.state.DateOfBirth!}
                    onChange={this.updateBinding}
                  />
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col>
              <Button size="lg" color="primary" onClick={this.savePerson}>保存</Button>
            </Col>
            <Col>
              <Button size="lg" color="secondary" onClick={this.clear}>重置</Button>
            </Col>
          </Row>
          <Row><FormValidation CurrentState={this.state} CanSave={this.userCanSave} /></Row>
        </Col>
        <Col>
          <Col>
            <Row>
              <Col>{people}</Col>
            </Row>
            <Row>
              <Col lg="6">
                <Button size="lg" color="success" onClick={this.loadPeople}>
                  加载联系人
                </Button>
              </Col>
              <Col lg="6">
                <Button size="lg" color="info" onClick={this.clear}>
                  创建联系人
                </Button>
              </Col>
            </Row>
          </Col>
        </Col>
      </Row>
    );
  }

  private async DeletePerson(person : string) {
    const foundPerson = this.people.find((element : IPersonState) => {
      return element.PersonId === person;
    });
    if (!foundPerson) {
      return;
    }
    const personState : IRecordState = new RecordState();
    personState.IsActive = false;
    const state : PersonRecord = {...foundPerson, ...personState};
    await this.dataLayer.Update(state);
    this.loadPeople();
    this.clear();
  }

  private loadPeople () {
    this.people = new Array<PersonRecord>();
    this.dataLayer.Read().then(people => {
      this.people = people;
      this.setState(this.state);
    });
  }

  private setActive = (event : any) => {
    const person : string = event.target.value;
    const state = this.people.find((element : IPersonState) => {
      return element.PersonId === person;
    });
    if (state) {
      this.setState(state);
    }
  }

  private savePerson = () => {
    if (!this.canSave) {
      alert('不能提交，请重新检查表单信息');
      return;
    }
    const personState : IRecordState = new RecordState();
    personState.IsActive = true;
    const state : PersonRecord = {...this.state, ...personState};
    if (state.PersonId === "") {
      state.PersonId = Date.now().toString();
      this.dataLayer.Create(state);
      this.loadPeople();
      this.clear();
    }
    else {
      this.dataLayer.Update(state).then(rsn => this.loadPeople());
    }
  }

  private clear = () => {
    this.setState(this.defaultState);
  }

  private userCanSave = (hasErrors: boolean) => {
    this.canSave = hasErrors;
  }

  private updateBinding = (event: any) => {
    switch (event.target.id) {
      case "firstName":
        this.setState({ FirstName: event.target.value });
        break;
      case "lastName":
        this.setState({ LastName: event.target.value });
        break;
      case "addr1":
        this.setState({ Address1: event.target.value });
        break;
      case "addr2":
        this.setState({ Address2: event.target.value });
        break;
      case "town":
        this.setState({ Town: event.target.value });
        break;
      case "country":
        this.setState({ Country: event.target.value });
        break;
      case "postcode":
        this.setState({ Postcode: event.target.value });
        break;
      case "phoneNumber":
        this.setState({ PhoneNumber: event.target.value });
        break;
      case "dateOfBirth":
        this.setState({ DateOfBirth: event.target.value });
        break;
    }
  };
}
